package com.xy.net.retrofit;

import android.content.Context;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import com.xy.net.OkHttpUtils;


import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by John on 2016/12/9.
 */

public class RetrofitUtils {

    private Context context;
    private static RetrofitUtils instance;

    private RetrofitUtils(Context context) {
        this.context = context;
    }

    public static RetrofitUtils getInstance(Context context) {
        if (instance == null) {
            synchronized (RetrofitUtils.class) {
                if (instance == null) {
                    instance = new RetrofitUtils(context);
                }
            }
        }
        return instance;
    }

    private Retrofit initNet(String baseUrl, boolean isCache) {
        return new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(OkHttpUtils.getInstance(context).initNet(isCache))
                .baseUrl(baseUrl)
                .build();
    }

    public void get(String url, boolean isCache, Map parameters, Observer<ResponseBody> Observer) {
        Retrofit retrofit = initNet(url, isCache);
        ApiService apiService = retrofit.create(ApiService.class);
        apiService.asynGet(url, parameters)
                .compose(new SwitchTransformer())
                .subscribe(Observer);
    }

    public ApiService post(String url, boolean isCache, Map parameters, Observer<ResponseBody> Observer) {
        Retrofit retrofit = initNet(url, isCache);
        ApiService apiService = retrofit.create(ApiService.class);
         apiService.asynPost(url, parameters)
                .compose(new SwitchTransformer())
                .subscribe(Observer);
        return apiService;
    }

    private class SwitchTransformer implements ObservableTransformer {
        @Override
        public ObservableSource apply(Observable upstream) {
            return upstream
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }
    }
}
